from logging import getLogger

from app.core.exceptions import APIException
from app.core.i18n import t
from app.core.security import invalidate_all_user_tokens
from app.models.user_model import UserModel

logger = getLogger(__name__)


class AdminAuthService:
    """管理员认证服务类"""

    @classmethod
    async def kickout_user(cls, user_id: int) -> bool:
        """踢出用户（使其所有令牌失效）"""
        user = await UserModel.get_or_none(id=user_id)
        if not user:
            raise APIException(message=t("error.user.not_found"))

        # 使用户的所有令牌失效
        success = await invalidate_all_user_tokens(user_id)
        if not success:
            raise APIException(message=t("error.auth.kickout_failed"))

        return True

    @classmethod
    async def force_logout(cls, user_id: int) -> bool:
        """强制用户登出"""
        return await cls.kickout_user(user_id)

    @classmethod
    async def disable_user(cls, user_id: int) -> bool:
        """禁用用户账号"""
        user = await UserModel.get_or_none(id=user_id)
        if not user:
            raise APIException(message=t("error.user.not_found"))

        # 禁用用户
        user.is_active = False
        await user.save()

        # 使用户的所有令牌失效
        await cls.kickout_user(user_id)

        return True

    @classmethod
    async def enable_user(cls, user_id: int) -> bool:
        """启用用户账号"""
        user = await UserModel.get_or_none(id=user_id)
        if not user:
            raise APIException(message=t("error.user.not_found"))

        # 启用用户
        user.is_active = True
        await user.save()

        return True
